package com.tools.scanner.gson

import android.text.TextUtils
import com.google.gson.Gson
import com.google.gson.JsonDeserializationContext
import com.google.gson.JsonDeserializer
import com.google.gson.JsonElement
import com.google.gson.reflect.TypeToken
import com.google.mlkit.vision.barcode.common.Barcode
import java.lang.reflect.Type

class ContactDeserializer : JsonDeserializer<Barcode.ContactInfo> {
    override fun deserialize(
        json: JsonElement,
        typeOfT: Type,
        context: JsonDeserializationContext
    ): Barcode.ContactInfo {
        val gson = Gson()

        val jsonObject = json.asJsonObject


        val zzaElement = jsonObject.get("zza")
        val zza = if (zzaElement == null) {
            null
        } else {
            gson.fromJson(gson.toJson(zzaElement), Barcode.PersonName::class.java)
        }

        val zzb = jsonObject.get("zzb")?.asString
        val zzc = jsonObject.get("zzc")?.asString

        val zzdElement = jsonObject.get("zzd")
        val zzd: List<Barcode.Phone> = if (zzdElement == null) {
            ArrayList()
        } else {
            val listType = object : TypeToken<List<Barcode.Phone>>() {}.type
            Gson().fromJson(
                gson.toJson(zzdElement),
                listType
            ) as List<Barcode.Phone>
        }


        val zzeElement = jsonObject.get("zze")
        val zze: List<Barcode.Email> = if (zzeElement == null) {
            ArrayList()
        } else {
            val listType = object : TypeToken<List<Barcode.Email>>() {}.type
            Gson().fromJson(
                gson.toJson(zzeElement),
                listType
            ) as List<Barcode.Email>
        }

        val zzfElement = jsonObject.get("zzf")
        val zzf: List<String> = if (zzfElement == null) {
            ArrayList()
        } else {
            val listType = object : TypeToken<List<String>>() {}.type
            Gson().fromJson(
                gson.toJson(zzfElement),
                listType
            ) as List<String>
        }

        val zzgElement = jsonObject.get("zzg")
        val zzg: List<Barcode.Address> = if (zzgElement == null) {
            ArrayList()
        } else {
            val listType = object : TypeToken<List<Barcode.Address>>() {}.type
            Gson().fromJson(
                gson.toJson(zzgElement),
                listType
            ) as List<Barcode.Address>
        }

        return Barcode.ContactInfo(zza, zzb, zzc, zzd, zze, zzf, zzg)
    }
}